﻿using Microsoft.VisualStudio.TestTools.UnitTesting;
using Moq;
using System.Data.Entity;
using System.Linq;
using Emico.Data.Entity.Tests.Repository;
using Emico.Data.Entity.Tests.Repository.Imples;
using Emico.Data.Entity.Repository;

namespace Emico.Data.Entity.Tests
{
    [TestClass]
    public class SimpleTest
    {
        [TestMethod]
        public void TestCreate()
        {
            var mockSet = new Mock<DbSet<Simple>>();
            var mockContextWrapper = new Mock<IDbContextWrapper>();
            mockContextWrapper.Setup(c => c.Set<Simple>()).Returns(mockSet.Object);

            using (TestContextUnitOfWork uw = new TestContextUnitOfWork(mockContextWrapper.Object))
            {                
                Simple simple = new Simple();
                simple.Columns = "Col";

                var repository = new SimpleRepository(mockContextWrapper.Object);
                repository.Add(simple);
                uw.Commit();

                mockSet.Verify(m => m.Add(It.IsAny<Simple>()), Times.Once());
                mockContextWrapper.Verify(m => m.SaveChanges(), Times.Once());
            }
        }

        [TestMethod]
        public void TestRead()
        {
            Simple simple = new Simple { Id = 1 };
            var data = new Simple[] { simple }.AsQueryable();

            var mockSet = new Mock<DbSet<Simple>>();
            mockSet.As<IQueryable<Simple>>().Setup(m => m.Provider).Returns(data.Provider);
            mockSet.As<IQueryable<Simple>>().Setup(m => m.Expression).Returns(data.Expression);
            mockSet.As<IQueryable<Simple>>().Setup(m => m.ElementType).Returns(data.ElementType);
            mockSet.As<IQueryable<Simple>>().Setup(m => m.GetEnumerator()).Returns(data.GetEnumerator());

            var mockContext = new Mock<TestContext>();
            var mockContextWrapper = new Mock<IDbContextWrapper>();
            mockContextWrapper.Setup(c => c.Set<Simple>()).Returns(mockSet.Object);

            using (TestContextUnitOfWork uw = new TestContextUnitOfWork(mockContextWrapper.Object))
            {
                var repository = new SimpleRepository(mockContextWrapper.Object);
                Simple result = repository.FirstOrDefault(s => s.Id == simple.Id);
                Assert.AreSame(simple, result);
            }
        }
    }
}
